package com.tancire.web.controller.platform.system;

import cn.hutool.core.util.IdUtil;
import com.tancire.common.constant.CacheConstants;
import com.tancire.common.constant.Constants;
import com.tancire.common.core.domain.AjaxResult;
import com.tancire.common.core.domain.entity.SysMenu;
import com.tancire.common.core.domain.entity.SysUser;
import com.tancire.common.core.domain.model.LoginBody;
import com.tancire.common.core.redis.RedisCache;
import com.tancire.common.enums.UserSource;
import com.tancire.common.exception.user.UserWxOpenIdException;
import com.tancire.common.utils.SecurityUtils;
import com.tancire.common.utils.StringUtils;
import com.tancire.common.utils.uuid.IdUtils;
import com.tancire.domain.SnsBean;
import com.tancire.framework.web.service.HeaderService;
import com.tancire.framework.web.service.SysLoginService;
import com.tancire.framework.web.service.SysPermissionService;
import com.tancire.framework.web.service.TokenService;
import com.tancire.member.domain.Member;
import com.tancire.member.service.IMemberService;
import com.tancire.system.service.ISysMenuService;
import com.tancire.wxapp.WxappRemoteNet;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {
    @Resource
    private SysLoginService loginService;

    @Resource
    private ISysMenuService menuService;

    @Resource
    private SysPermissionService permissionService;

    @Resource
    private WxappRemoteNet wxappRemoteNet;

    @Resource
    private RedisCache redisCache;

    @Resource
    private IMemberService memberService;

    @Resource
    private HeaderService headerService;

    @Resource
    private TokenService tokenService;


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult systemLogin(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), true);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 自动登录接口
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login/auto")
    public AjaxResult autoLogin(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        String code = loginBody.getCode();
        String username = tokenService.getUsernameFromToken(code);
        if (StringUtils.isBlank(loginBody.getUsername()) || !loginBody.getUsername().equals(username)) {
            return AjaxResult.error("检测到非法登录");
        }
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), false);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 微信登录
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login/wx")
    public AjaxResult wxLogin(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 调用微信获取openId
        SnsBean snsBean = wxappRemoteNet.getOpenId(loginBody.getCode());
        String openid = snsBean.getOpenid();
        if (StringUtils.isBlank(openid)) {
            throw new UserWxOpenIdException();
        }
        // 2024-05-20 代码实现优化
        Member member = memberService.selectMemberByOpenId(openid);
        if (null == member || null == member.getMemberId()) {
            // 没有登录过，创建账号
            Member user = new Member();
            user.setAccount(IdUtil.getSnowflakeNextId() + "");
            user.setPassword(SecurityUtils.encryptPassword(IdUtil.fastSimpleUUID()));
            user.setOpenId(openid);
            user.setSessionKey(snsBean.getSessionKey());
            memberService.insertMember(user);
            // 塞回去数据
            member = user;
        }
        // 获取openId，用于登录
        String token = loginService.login(member.getAccount(), Constants.NO_PASSWORD_CERTIFY, loginBody.getCode(),
                loginBody.getUuid(), false);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = new HashSet<>();
        // 权限集合
        Set<String> permissions = new HashSet<>();
        // 判断不同类型用户
        UserSource source = headerService.getSource();
        if (UserSource.SYSTEM == source) {
            roles = permissionService.getRolePermission(user);
            permissions = permissionService.getMenuPermission(user);
        } else if (UserSource.MEMBER == source) {
            permissions.add("member:user:union");
        }

        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 校验登录状态
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/check/token")
    public AjaxResult checkToken(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        String code = loginBody.getCode();
        // 生成令牌
        boolean hasLive = loginService.checkToken(code);
        if (hasLive) {
            ajax.put("live", 1);
        } else {
            // 登录失效生成自动登录的验证 key
            String uuid = IdUtils.simpleUUID();
            String verifyKey = CacheConstants.AUTO_LOGIN_KEY + uuid;
            redisCache.setCacheObject(verifyKey, StringUtils.isBlank(code) ? "jump" : code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
            ajax.put("live", 0);
            ajax.put("temp", uuid);
        }
        return ajax;
    }
}
